package com.yoyo.schedule.strategy;

import lombok.extern.slf4j.Slf4j;

/**
 * 初始化线程
 */
@Slf4j
public class InitThread extends Thread {

    ScheduleFactory scheduleFactory;
    volatile boolean isStop = false;

    public InitThread(ScheduleFactory scheduleFactory) {
        this.scheduleFactory = scheduleFactory;
    }

    public void stopThread() {
        this.isStop = true;
    }

    @Override
    public void run() {
        scheduleFactory.lock.lock();
        try {
            int count = 0;
            while (scheduleFactory.zooKeeperManager.zooKeeperIsConnected() == false) {
                count = count + 1;
                if (count % 50 == 0) {
                    scheduleFactory.errorMessage = "zooKeeper is connecting ......" + scheduleFactory.zooKeeperManager.getZooKeeperConnectString() + " spendTime:" + count * 20 + "(ms)";
                    log.error(scheduleFactory.errorMessage);
                }
                Thread.sleep(20);
                if (this.isStop == true)//快速停止 只是用于配置信息错误的情况
                {
                    return;
                }
            }
            scheduleFactory.doInit();
        } catch (Throwable e) {
            log.error(e.getMessage(), e);
        } finally {
            scheduleFactory.lock.unlock();
        }

    }

}
